// *************************************************************************************************
//
// MK3D Engine
// --------------------------------------
// Copyright (C) 2007-2011 Zeb (mailto: zebbey@gmail.com)
//
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
// *************************************************************************************************

#include "mk_header.h"
#include "mk_win32_app.h"

namespace MK3DE
{
	static CWin32App* __app = NULL;
	LRESULT WINAPI __MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
	{
		if (__app)
			return __app->MsgProc(hWnd, msg, wParam, lParam);

		return DefWindowProc(hWnd, msg, wParam, lParam);
	}

	CWin32App::CWin32App() :
	_hInstance(NULL),
		_hWnd(NULL)
	{

	}

	CWin32App::~CWin32App()
	{

	}

	LRESULT CWin32App::MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
	{
		switch( msg )
		{
		case WM_DESTROY:
			PostQuitMessage(0);
			return 0;
		}

		return DefWindowProc(hWnd, msg, wParam, lParam);
	}

	BOOL CWin32App::Create(HINSTANCE hInstance, const char* title, DWORD width, DWORD height)
	{
		WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, __MsgProc, 0L, 0L, 
			hInstance, NULL, LoadCursor(NULL, IDC_ARROW), (HBRUSH)(COLOR_BACKGROUND), 
			NULL, title, NULL };

		if (!RegisterClassEx(&wc))
			return FALSE;

		DWORD style = WS_CAPTION | WS_BORDER | WS_MINIMIZEBOX | WS_SYSMENU;
		RECT rc = { 0, 0, width, height };
		AdjustWindowRect(&rc, style, FALSE);

		_hWnd = CreateWindow(title, title, style,
			0, 0, rc.right - rc.left, rc.bottom - rc.top,
			GetDesktopWindow(), NULL, wc.hInstance, NULL);

		if (!_hWnd)
			return FALSE;

		ShowWindow(_hWnd, SW_SHOWDEFAULT);
		UpdateWindow(_hWnd );

		_hInstance = hInstance;
		_title = title;
		__app = this;
		return TRUE;
	}

	void CWin32App::MainLoop()
	{
		MSG msg; 
		ZeroMemory(&msg, sizeof(msg));
		while (msg.message!=WM_QUIT)
		{
			if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE ))
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
			else
			{
				Active();
			}
		}
	}

	void CWin32App::Destroy()
	{
		UnregisterClass(_title.c_str(), _hInstance);
	}
}
